# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django import newforms as forms
from django.contrib.auth.models import Group,Permission


class SimpleGroup(forms.Form):
    name = forms.CharField(label="Nome", required=True)

    #def __init__(self, *args, **kwargs):
        #super(SimpleGroup,self).__init__(*args,**kwargs)
    #    pass
    
    def save(self, *args, **kwargs):
        g = Group()
        g.name = self.cleaned_data['name']
        g.save()


class ModGroup(forms.Form):
    all_permission = forms.MultipleChoiceField()
    owned_permission = forms.MultipleChoiceField()
    base_group = None
    def __init__(self,g, *args, **kwargs):
        plist = [ (e.id , e.name) for e in Permission.objects.exclude(id__in= [x.id for x in g.permissions.all()])]
        print "outprova"
        self.base_group = g
        self.base_fields['all_permission'].choices = plist
        self.base_fields['owned_permission'].choices = [(x.id, x.name) for x in g.permissions.all()]
        self.base_fields['owned_permission'].required = False
        self.base_fields['all_permission'].required=False
        print dir(self.base_fields['all_permission'])
        super(ModGroup,self).__init__(*args,**kwargs)

    def save(self):
        added_perm = self.cleaned_data['all_permission']
        deleted_perm = self.cleaned_data['owned_permission']
        for a in added_perm:
            self.base_group.permissions.add(a)
        self.base_group.save()
        for a in deleted_perm:
            self.base_group.permissions.remove(a)

